#region Imported Namespaces
using System;
using InsightPolicy = PHSRAG.Insight21.Policy;
using InsightHumans = PHSRAG.Insight21.Humans;
using InsightUtility = PHSRAG.Utility;
using WorFlowInterface = Workflow.NET.Engine.Interfaces;
using WorkFlowEngine = Workflow.NET.Engine;
using Workflow.NET;
using System.Threading;

#endregion

namespace PHSRAG.Insight21.InsightWorkFlow
{
	#region Class MoveToRex
	/// <summary>
	/// This is a Skelta workflow custom action class. This class is moving Protocol to Rex and changes the status to Pending
	/// IActionRun is Skelta interface to implement custom actions. 
	/// Actions.xml of particular application needs to be configured so that this action
	/// becomes accesible from Skelta Workflow Manager control under List of Actions -> Custom Actions. 
	/// This action does not take any parameter. 
	/// </summary>
	public class MoveToRex:Workflow.NET.Engine.Interfaces.IActionRun		
	{
		#region Private Constnts
		private const string RexDatabase = "Rex";
		#endregion
		/// <summary>
		/// Default constructor
		/// </summary>
		public MoveToRex()
		{
			
		}
		/// <summary>
		/// This custom action moves ProtocolProces to Rex database and also changes status of the Protocol Process to Pending.
		/// </summary>
		/// <param name="executionId">Workflow execution Id - a unique id used for each workflow item</param>
		/// <param name="executionDetailsId">Execution detail Id - Id used for execution detail table</param>
		/// <param name="currentContext">Context class which encapsulates all the information about the executing Workflow.</param>
		/// <param name="currentAction">Current Workflow action</param>
		/// <param name="inlinkOutput">Output in string format which has come from the step before this step</param>
		/// <param name="retry">Boolean retry variable</param>
		/// <param name="output">Output value which is used by Skelta Workflow manager to takce certain path in the process.</param>
		/// <returns>The result of an action execution. Either execution is complete or action is in sleep mode.  </returns>
		public  WorFlowInterface.ActionResult Run(int executionId,int executionDetailsId,WorkFlowEngine.Context currentContext,Action currentAction,string inlinkOutput,bool retry,out string output)
		{
            /*SOAP Station Changes*/
            MoveToRexService.HumansWse HumansWse = new PHSRAG.Insight21.InsightWorkFlow.MoveToRexService.HumansWse();

            //Get the service account credentials
            string serviceAccount = HumansWorkFlow.SOAPServiceAccount;
            string serviceAccountPwd = HumansWorkFlow.SOAPServiceAccountPwd;            

            //Create our UsernameToken and supply the consumer credentials... 
            Microsoft.Web.Services3.Design.UsernameTokenProvider user =
                new Microsoft.Web.Services3.Design.UsernameTokenProvider(@"partners\" + serviceAccount, serviceAccountPwd);

            //Create the policy assertion... 
            Microsoft.Web.Services3.Design.UsernameOverTransportAssertion assert = new Microsoft.Web.Services3.Design.UsernameOverTransportAssertion();
            assert.UsernameTokenProvider = user;
            assert.ServiceActor = @"http://partners.org/security/webservicesecurity";
            //Set the policy... 
            HumansWse.SetPolicy(new Microsoft.Web.Services3.Design.Policy(assert));
            ///*SOAP Station Changes END*/

            output = null;
            Log logger = currentContext.log;
            string returnMessage = string.Empty;
            HumansWorkFlow humansWF = new HumansWorkFlow(new InsightPolicy.NullCachePolicy());

            try
            {
                //System.Diagnostics.Debugger.Break();
                object insightApplicationName = currentContext.Contents["insightApplicationName"];
                HumansWorkFlow.InsightApplicationName = (null == insightApplicationName) ? string.Empty : ((Content)insightApplicationName).Value.ToString();
                //HumansWorkFlow.InsightApplicationName = currentContext.Contents["insightApplicationName"].Value.ToString();
                Thread.SetData(Thread.GetNamedDataSlot("Connections"), HumansWorkFlow.Connections);

                int protocolProcessId = HumansWorkFlow.GetProtocolProcessIdForWorkflowItem(executionId);

                HumansWse.Url = HumansWorkFlow.InsightWebService;
                returnMessage = HumansWse.MoveProcessToRex(HumansWorkFlow.InsightConnection, HumansWorkFlow.RexConnection, protocolProcessId);

                if (returnMessage.Equals("success", StringComparison.CurrentCultureIgnoreCase))
                {
                    //Move to Rex is succesful, now change the status to Pending				
                    humansWF.SetProtocolProcessStatus(InsightHumans.Constants.ProtocolProcessStatus.Pending, HumansWorkFlow.GetProtocolProcessIdForWorkflowItem(executionId), currentContext.Contents["pptype"].Value.ToString());
                    humansWF.SetMovedToRexFlag(HumansWorkFlow.GetProtocolProcessIdForWorkflowItem(executionId));
                }
                else
                {
                    throw (new Exception("Problem in MoveToRex Service: " + returnMessage));
                }
                output = "Success";
            }
            catch (Exception ex)
            {
                logger.LogMessage(ReasonConst.Error, String.Format("{0} : {1} : {2} : {3}", "Unable to move Protocol Process to Rex database in MoveToRex.Run()", ex.Message, returnMessage, ex.ToString()));
                output = "Failure";
            }
            finally
            {
                humansWF.Dispose();
            }
            return WorFlowInterface.ActionResult.Completed;

        }
		
		/// <summary>
		/// Gets the web control to be displayed in the activity list for this action. No user interface is implemented for
		/// this action. So it returns null.
		/// </summary>
		/// <returns>IActivityWebUIHandler - Interface that allows an object to implement a custom document view Control.</returns>
		public virtual Workflow.NET.Interfaces.IActivityWebUIHandler GetActivityWebUIHandler()
		{
			return null;
		} 

	}
	#endregion
}
